package com.smart.manager.pop.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import com.smart.common.entities.core.Page;
import com.smart.manager.pop.entities.body.RActivityMain;
import com.smart.manager.pop.entities.enums.HdState;
import com.smart.manager.pop.entities.enums.RegisterKind;
import com.smart.manager.pop.entities.models.PopActivityMain;
import com.smart.manager.pop.entities.models.query.QPopActivityMain;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 活动注册 数据处理接口
 *
 * @author Administrator
 */

@Log4j2
@Service
@RequiredArgsConstructor
public class ActivityMainRepository {

        private final AsyncService asyncService;

    public Page<PopActivityMain> pageList(RActivityMain.SearchBody search) {


        QPopActivityMain query = new QPopActivityMain();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows()).order().id.desc();
        return new Page<PopActivityMain>().load(query.findPagedList());
    }

    /**
     * 添加
     *
     * @param form 形式
     */
    public void add(RActivityMain.EditBody form) {

        PopActivityMain paymentWechat = BeanUtil.copyProperties(form, PopActivityMain.class);
        paymentWechat.save();

    }

    /**
     * 更新
     *
     * @param id   id
     * @param form 形式
     */
    public void update(Long id, RActivityMain.EditBody form) {
        PopActivityMain record = new QPopActivityMain().id.eq(id).findOne();
        Assert.notNull(record, "活动信息不存在");
        Long posterId = record.getPosterId();
        BeanUtil.copyProperties(form, record);
        record.update();
        //不相同则需要 更新图片
        if (ObjUtil.notEqual(form.getPosterId(),posterId)) {
            //找到所有活动的PopC2cAttend  activity 的id , 吧share_data重新生成图片
            asyncService.getActivityAttendUpdate(record);
        }
    }



    /**
     * 批量删除
     *
     * @param idList id列表
     * @return int
     */
    public int delByIds(List<Long> idList) {

        return DB.deleteAll(PopActivityMain.class, idList);

    }


    /**
     * 根据活动性质获取最新的一个活动

     * @return {@code PopActivityMain}
     */
    public PopActivityMain getById(long id ) {
        PopActivityMain record = new QPopActivityMain()
                .id.eq(id)
                .kind.eq(RegisterKind.C2C).state.eq(HdState.NORMAL).setMaxRows(1).order().id.desc().findOne();
        Assert.notNull(record, "当前系统没有配置对应的活动");
        return record;
    }

    public PopActivityMain readOne(Long activityId) {
        PopActivityMain record = new QPopActivityMain().kind.eq(RegisterKind.C2C).id.eq(activityId).setMaxRows(1).findOne();
        Assert.notNull(record , "邀请失败:注册活动不存在") ;
        Assert.equals(record.getState() ,HdState.NORMAL , "邀请失败:注册活动已到期");
        return record;
    }
}
